package com.uzai.console.service.tb.tbpunishorder.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkScPunishOrderGetRequest;
import com.taobao.api.response.TbkScPunishOrderGetResponse;
import com.uzai.common.constants.UserExtKeys;
import com.uzai.common.dto.notice.AppNoticeDto;
import com.uzai.common.dto.notice.AppNoticeOrderMsg;
import com.uzai.common.entity.User;
import com.uzai.common.enums.*;
import com.uzai.common.enums.notice.NoticeBusinessTypeEnum;
import com.uzai.common.enums.notice.NoticeOrderScenesEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.DateUtil;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.common.utils.ZipUtils;
import com.uzai.console.component.excel.template.TbPunishOrderExcelDemo;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.Const;
import com.uzai.console.dto.feign.orderreport.OrderReportDto;
import com.uzai.console.dto.module.merchant.DeviceTypeQuery;
import com.uzai.console.dto.remoteapi.UploadTbPunishOrderByUzaiToolBoxDto;
import com.uzai.console.dto.tb.tbpunishorder.*;
import com.uzai.console.dto.user.useraccdetail.UserAccDetailQuery;
import com.uzai.console.entity.*;
import com.uzai.console.enums.ExportInfoTypeEnum;
import com.uzai.console.enums.SmsType;
import com.uzai.console.enums.TbPunishOrderViolationTypesEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.cms.CmsParamReplaceService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.exportinfo.ExportInfoService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.tb.tbpunishorder.TbPunishOrderAddService;
import com.uzai.console.service.tb.tbpunishorder.TbPunishOrderService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.vo.exportinfo.ExportAmountVo;
import com.uzai.console.vo.module.merchant.MerchantDeviceTypeVo;
import com.uzai.console.vo.tb.tbpunishorder.TbPunishOrderAutoChargebackVo;
import com.uzai.console.vo.tb.tbpunishorder.TbPunishOrderExport;
import com.uzai.console.vo.tb.tbpunishorder.TbPunishOrderInfoVo;
import com.uzai.common.utils.Math;

import com.uzai.console.vo.wechatprivate.wxcontacts.WxContactsExport;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 淘宝处罚订单
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class TbPunishOrderServiceImpl implements TbPunishOrderService {

    Logger logger = LoggerFactory.getLogger(TbPunishOrderServiceImpl.class);

    @Autowired
    private TbPunishOrderMapper tbPunishOrderMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbPunishOrderAddService tbPunishOrderAddService;
    @Autowired
    private UserAccDetailMapper userAccDetailMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private CmsParamReplaceService cmsParamReplaceService;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ExportInfoService exportInfoService;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerServicen;

    /**
     * 查询淘宝处罚订单列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbPunishOrderQuery
     * @return null
     */
    public Page<TbPunishOrderInfoVo> findTbPunishOrderList(TbPunishOrderQuery tbPunishOrderQuery){
        //新建返回到页面的LIST对象
        List<TbPunishOrderInfoVo> tbPunishOrderPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<TbPunishOrder> page = new Page<>();
        tbPunishOrderQuery.convert(page);
        ArrayList<TbPunishOrder> tbPunishOrderList =  tbPunishOrderMapper.findByList(page, tbPunishOrderQuery);
        if(tbPunishOrderList != null && tbPunishOrderList.size() > 0){
            for (TbPunishOrder tbPunishOrder : tbPunishOrderList){
                TbPunishOrderInfoVo tbPunishOrderPageVo = new TbPunishOrderInfoVo();
                BeanUtils.copyProperties(tbPunishOrder, tbPunishOrderPageVo);
                //淘宝订单创建时间
                tbPunishOrderPageVo.setCreatedt(tbPunishOrder.getTkTradeCreateTime());

                TbToken tbToken = tbTokenMapper.selectById(tbPunishOrder.getTbTokenId(), tbPunishOrder.getMerId());
                if(tbToken != null){
                    tbPunishOrderPageVo.setUserName(tbToken.getUserName());
                }

                //淘宝订单信息
                tbPunishOrderPageVo.setCommission(0.00D); //默认为0
                if(tbPunishOrder.getOrderId() != null){
                    TbOrder tbOrder = tbOrderMapper.selectById(tbPunishOrder.getOrderId(), tbPunishOrderQuery.getMerId());
                    if(tbOrder != null){
                        tbPunishOrderPageVo.setCommission(Tools.getDouble(tbOrder.getCommission()));
                    }
                }

                tbPunishOrderPageVoList.add(tbPunishOrderPageVo);
            }
        }

        //返回到页面分页对象
        Page<TbPunishOrderInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(tbPunishOrderPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 下载淘宝处罚订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbPunishOrderDownLoadDto
     * @return null
     */
    @Async("taskExecutor")
    public void downloadTbPunishOrder(TbPunishOrderDownLoadDto tbPunishOrderDownLoadDto){
        String paramDate = tbPunishOrderDownLoadDto.getQueryMonth()+"-01 00:00:00";
        int paramMonth = 0;
        try {
            paramMonth = DateUtil.getTime(com.taobao.api.internal.util.StringUtils.parseDateTime(paramDate));
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        int currMonth = DateUtil.getTime(DateUtil.getBeginDayOfMonth());

        if (paramMonth >= currMonth){
            //throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只能选择当月之前的月份");
        }

        //获取当前月的天数
        int days = Tools.getDaysOfMonth(com.taobao.api.internal.util.StringUtils.parseDateTime(paramDate));
        String paramDate_31 = tbPunishOrderDownLoadDto.getQueryMonth()+"-31 00:00:00";
        List<Long> tbTokenIdList = tbPunishOrderDownLoadDto.getTbTokenIdList();
        if(tbTokenIdList != null && tbTokenIdList.size() > 0){
            //返利
            String tbApiUrl = uzaiConsoleSysConfig.getTbApiUrl();
            String tbAppkey = uzaiConsoleSysConfig.getTbAppkey();
            String tbAppsecret = uzaiConsoleSysConfig.getTbAppsecret();
            TaobaoClient client = new DefaultTaobaoClient(tbApiUrl, tbAppkey, tbAppsecret);

            //导购
            String tbApiUrl_dg = uzaiConsoleSysConfig.getTbApiUrl();
            String tbAppkey_dg = uzaiConsoleSysConfig.getTbAppkeyDg();
            String tbAppsecret_dg = uzaiConsoleSysConfig.getTbAppsecretDg();
            TaobaoClient client_dg = new DefaultTaobaoClient(tbApiUrl_dg, tbAppkey_dg, tbAppsecret_dg);


            for (Long tbTokenId : tbTokenIdList){
                TbToken tbToken = tbTokenMapper.selectById(tbTokenId, tbPunishOrderDownLoadDto.getMerId());
                if (tbToken==null){
                    //throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.PARAM_ERROR);
                    continue;
                }

                //导购联盟
                if(Tools.getInteger(tbToken.getTurnlink()).intValue() == 0){
                    //处理淘宝处罚订单
                    dealTbPunishOrder(client, paramDate, tbToken);

                    //大于30天,则还得单独拉取31号的订单
                    if(days > 30 ){

                        //处理淘宝处罚订单
                        dealTbPunishOrder(client, paramDate_31, tbToken);
                    }
                }else{//导购
                    //处理淘宝处罚订单
                    dealTbPunishOrder(client_dg, paramDate, tbToken);
                    //大于30天,则还得单独拉取31号的订单
                    if(days > 30 ){
                        //处理淘宝处罚订单
                        dealTbPunishOrder(client_dg, paramDate_31, tbToken);
                    }
                }
            }
        }
    }

    /**
     * 处理淘宝处罚订单业务功能
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbToken
     * @param date 查询开始订单创建时间("yyyy-MM-dd HH:mm:ss")
     * @return null
     */
    public void dealTbPunishOrder(TaobaoClient client, String date, TbToken tbToken){
        Long totalCount = getOrders(client, date,1l, tbToken);
        if (totalCount != null && totalCount > 0) {
            long pageno = totalCount / 20 + 1;
            for (int i = 2; i <=pageno; i++) {
                getOrders(client, date, (long) i, tbToken);
            }
        }
    }

    /**
     * 扣款淘宝处罚订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbPunishOrderIdDto
     * @return null
     */
    @Transactional
    public void takeOffTbPunishOrder(TbPunishOrderIdDto tbPunishOrderIdDto){
        int now = DateUtil.getTime();
        //查询扣款订单状态
        TbPunishOrder tbPunishOrder = tbPunishOrderMapper.selectById(tbPunishOrderIdDto.getId(), tbPunishOrderIdDto.getMerId());
        if(tbPunishOrder == null || tbPunishOrder.getStatus() == 1){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该订单不存在或已扣款");
        }

        //查询订单订单状态
        TbOrder tbOrder = tbOrderMapper.selectById(tbPunishOrder.getOrderId(), tbPunishOrderIdDto.getMerId());
        if(tbOrder !=null){
            //订单处于结算状态，且 已返利 且 不是免单订单，需要追回返利-扣款
            if(tbOrder.getStatus() == 1 && tbOrder.getReStatus() == 1 && Tools.getInteger(tbOrder.getFree()) != 1){
                //绑定会员
                if(tbOrder.getUserId() != null){
                    //判断是否已经有扣款明细，如果有，则跳过去
//                    UserAccDetailQuery userAccDetailQuery = new UserAccDetailQuery();
//                    userAccDetailQuery.setMerId(tbPunishOrderIdDto.getMerId());
//                    userAccDetailQuery.setType(AccDetailTypeEnum.PUB_ORDER_SUB.getValue());
//                    userAccDetailQuery.setOrderId(tbOrder.getChildOrderNo());
//                    List<UserAccDetail> userAccDetailList = userAccDetailMapper.findByList(userAccDetailQuery);

                    //落叶运营商，执行订单号模糊查询
                    UserAccDetail userAccDetail = null;
                    if(tbPunishOrderIdDto.getMerId().longValue() == 1249921860559478786L){
                        //userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndOrderIdLike(tbOrder.getUserId(), AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), tbOrder.getChildOrderNo());
                        //2023-12-14修改，不缺分落叶和其他运营商
                        userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndOrderId(tbOrder.getUserId(), AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), tbOrder.getChildOrderNo());

                    }else{
                        userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndOrderId(tbOrder.getUserId(), AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), tbOrder.getChildOrderNo());
                    }

                    //还未产生扣款明细则新增加，如果有了就跳过不新增
                    if(userAccDetail == null){
                        //用户返利
                        double reUserBal = tbOrder.getReUserBal();
                        //上级返利
                        double reParentUserBal = tbOrder.getReParentBal();
                        //上上级返利
                        double reSlParentUserBal = tbOrder.getReSlParentBal();
                        //代理返利
                        double reAgentBal = tbOrder.getReAgentBal();
                        //上级代理返利
                        double reSlAgentBal = tbOrder.getReSlAgentBal();
                        //合伙人返利
                        double rePartnerBal = tbOrder.getRePartnerBal();

                        String tradeNo = tbOrder.getParentOrderNo() + "_" + tbOrder.getChildOrderNo();

                        //查询用户信息
                        User user = userService.findUserInfo(tbOrder.getUserId(), tbOrder.getDeviceType(), tbOrder.getMerId());
                        if (user != null){
                            //扣款用户返利
                            updateBalance(reUserBal,0, now, user, AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), tbOrder.getChildOrderNo(),0l, tbOrder.getDeviceUniqueId(), tradeNo);

                            //上级返利
                            User parentUser = userService.findUserInfo(user.getParentId(), user.getDeviceType(), tbOrder.getMerId());
                            if(parentUser != null){
                                //扣款上级返利
                                updateBalance(reParentUserBal,0, now, parentUser, AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), tbOrder.getChildOrderNo(), user.getId(), tbOrder.getDeviceUniqueId(), tradeNo);

                                //上上级返利
                                User slParentUser = userService.findUserInfo(parentUser.getParentId(), user.getDeviceType(), tbOrder.getMerId());
                                if(slParentUser != null){
                                    //扣款上上级返利
                                    updateBalance(reSlParentUserBal,0, now, slParentUser, AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), tbOrder.getChildOrderNo(), user.getId(), tbOrder.getDeviceUniqueId(), tradeNo);
                                }
                            }

                            //代理人返利
                            User reAgenter = userService.findUserInfo(user.getAgentId(), user.getDeviceType(), tbOrder.getMerId());
                            if(reAgenter != null ){
                                //扣款代理人返利
                                updateBalance(reAgentBal,0, now, reAgenter, AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), tbOrder.getChildOrderNo(), user.getId(), tbOrder.getDeviceUniqueId(), tradeNo);

                                //上级代理人返利
                                User slAgenter = userService.findUserInfo(reAgenter.getAgentId(), user.getDeviceType(), tbOrder.getMerId());
                                if(slAgenter != null){
                                    //扣款上级代理返利
                                    updateBalance(reSlAgentBal,0, now, slAgenter, AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), tbOrder.getChildOrderNo(), user.getId(), tbOrder.getDeviceUniqueId(), tradeNo);
                                }
                            }

                            //合伙人返利
                            User partner = userService.findUserInfo(user.getPartnerId(), user.getDeviceType(), tbOrder.getMerId());
                            if(partner != null){
                                //扣款上级代理返利
                                updateBalance(rePartnerBal,0, now, partner, AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), tbOrder.getChildOrderNo(), user.getId(), tbOrder.getDeviceUniqueId(), tradeNo);
                            }

                            //发送订单维权回复消息
                            sendMsgForPunishOrder(user, tbOrder);
                        }
                    }

                    //修改扣款订单状态为已扣款
                    tbPunishOrder.setStatus(1);
                    tbPunishOrder.setUpdateTime(now);
                    tbPunishOrderMapper.updateByIdSelective(tbPunishOrder);

                    // 处理订单处罚
                    TbOrder tbOrder_old = new TbOrder();
                    tbOrder_old.setId(tbOrder.getId());
                    tbOrder_old.setMerId(tbOrder.getMerId());
                    tbOrder_old.setStatus(OrderStatusEnum.STATUS_PUNISH.getValue());
                    tbOrder_old.setReStatus(OrderReStatusEnum.RE_STATUS_BACK.getValue());
                    tbOrder_old.setUpdateTime(now);
                    tbOrder_old.setCommission(0.00D);
                    tbOrder_old.setCommissionRate(0.00D);
                    tbOrder_old.setProfit(0.00D);
                    tbOrder_old.setReUserBal(0.00D);
                    tbOrder_old.setReUserInte(0);
                    tbOrder_old.setReParentBal(0.00D);
                    tbOrder_old.setReAgentBal(0.00D);
                    tbOrder_old.setRePartnerBal(0.00D);
                    tbOrder_old.setReSlParentBal(0.00D);
                    tbOrder_old.setReSlAgentBal(0.00D);
                    tbOrder_old.setReOtherBal(0.00D);
                    tbOrder_old.setAlimamaShareFee(0.00D);
                    tbOrderMapper.updatePunishInfo(tbOrder_old);
                }else{ //未绑定会员
                    // 处理订单失效
                    TbOrder tbOrder_old = new TbOrder();
                    tbOrder_old.setId(tbOrder.getId());
                    tbOrder_old.setMerId(tbOrder.getMerId());
                    tbOrder_old.setStatus(OrderStatusEnum.STATUS_PUNISH.getValue());
                    tbOrder_old.setReStatus(OrderReStatusEnum.RE_STATUS_NO.getValue());
                    tbOrder_old.setUpdateTime(now);
                    tbOrder_old.setCommission(0.00D);
                    tbOrder_old.setCommissionRate(0.00D);
                    tbOrder_old.setProfit(0.00D);
                    tbOrder_old.setReUserBal(0.00D);
                    tbOrder_old.setReUserInte(0);
                    tbOrder_old.setReParentBal(0.00D);
                    tbOrder_old.setReAgentBal(0.00D);
                    tbOrder_old.setRePartnerBal(0.00D);
                    tbOrder_old.setReSlParentBal(0.00D);
                    tbOrder_old.setReSlAgentBal(0.00D);
                    tbOrder_old.setReOtherBal(0.00D);
                    tbOrder_old.setAlimamaShareFee(0.00D);
                    tbOrderMapper.updatePunishInfo(tbOrder_old);

                    //修改扣款订单状态为已扣款
                    tbPunishOrder.setStatus(1);
                    tbPunishOrder.setUpdateTime(now);
                    tbPunishOrderMapper.updateByIdSelective(tbPunishOrder);
                }
            }else{
                // 订单未返利
                // 处理订单失效
                TbOrder tbOrder_old = new TbOrder();
                tbOrder_old.setId(tbOrder.getId());
                tbOrder_old.setMerId(tbOrder.getMerId());
                tbOrder_old.setStatus(OrderStatusEnum.STATUS_PUNISH.getValue());
                tbOrder_old.setReStatus(OrderReStatusEnum.RE_STATUS_NO.getValue());
                tbOrder_old.setUpdateTime(now);
                tbOrder_old.setCommission(0.00D);
                tbOrder_old.setCommissionRate(0.00D);
                tbOrder_old.setProfit(0.00D);
                tbOrder_old.setReUserBal(0.00D);
                tbOrder_old.setReUserInte(0);
                tbOrder_old.setReParentBal(0.00D);
                tbOrder_old.setReAgentBal(0.00D);
                tbOrder_old.setRePartnerBal(0.00D);
                tbOrder_old.setReSlParentBal(0.00D);
                tbOrder_old.setReSlAgentBal(0.00D);
                tbOrder_old.setReOtherBal(0.00D);
                tbOrder_old.setAlimamaShareFee(0.00D);
                tbOrderMapper.updatePunishInfo(tbOrder_old);

                //修改扣款订单状态为已扣款
                tbPunishOrder.setStatus(1);
                tbPunishOrder.setUpdateTime(now);
                tbPunishOrderMapper.updateByIdSelective(tbPunishOrder);
            }

            //发送MQ，修改订单统计数据
            String userExtKey_tb = null;
            String userExtKey = null;
            if(tbOrder.getStatus().intValue() == OrderStatusEnum.STATUS_PAID_VALUE) { //付款订单
                userExtKey_tb = UserExtKeys.TbPayOrderCount;
                userExtKey = UserExtKeys.PayOrderCount;
            }else if(tbOrder.getStatus().intValue() == OrderStatusEnum.STATUS_SETTLED_VALUE){ //结算状态
                userExtKey_tb = UserExtKeys.TbSettleOrderCount;
                userExtKey = UserExtKeys.SettleOrderCount;
            }
            //不等于空，才发送MQ
            if(StringUtils.isNotBlank(userExtKey_tb)){
                OrderReportDto orderReportDto = new OrderReportDto();
                orderReportDto.setId(Tools.getStr(tbOrder.getParentOrderNo()) + Tools.getStr(tbOrder.getChildOrderNo()));
                orderReportDto.setKeys(Lists.newArrayList(userExtKey_tb, userExtKey));
                orderReportDto.setMerId(tbOrder.getMerId());
                orderReportDto.setUserId(tbOrder.getUserId());
                orderReportDto.setVal(-1);
                noticeMsgPushProducerServicen.sendOrderReportAsync(orderReportDto);
            }
        }
    }

    /**
     * 淘宝订单维权发送消息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param user
     * @param tbOrder
     * @return null
     */
    private void sendMsgForPunishOrder(User user, TbOrder tbOrder){

        if(user == null || tbOrder == null){
            return;
        }

        //APP会员发送APP推送消息
        if(DeviceTypeEnum.APP.getKey().equals(user.getDeviceType())){
            AppNoticeOrderMsg appNoticeOrderMsg = new AppNoticeOrderMsg();
            appNoticeOrderMsg.setOrderScene(NoticeOrderScenesEnum.order_punish.code); //处罚订单
            appNoticeOrderMsg.setMerId(tbOrder.getMerId());
            appNoticeOrderMsg.setChildOrderNo(tbOrder.getChildOrderNo());
            appNoticeOrderMsg.setParentOrderNo(tbOrder.getParentOrderNo());
            appNoticeOrderMsg.setRefundReBal(tbOrder.getReUserBal());
            appNoticeOrderMsg.setPlatform(PlatformTypeEnum.PT_TAOBAO.getId());
            //发送MQ消息
            AppNoticeDto appNoticeDto = new AppNoticeDto();
            appNoticeDto.setBusinessType(NoticeBusinessTypeEnum.order_notice.getCode());
            appNoticeDto.setMsgContent(JSONObject.toJSONString(appNoticeOrderMsg));
            noticeMsgPushProducerService.sendAppMessage(appNoticeDto);
            logger.info("发送App会员淘宝订单维权回复消息，para={}", JSONObject.toJSONString(appNoticeDto));

        }else{
            //如果提现记录的机器人不存在，则取会员默认客户端机器人
            Device device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), user.getDeviceType(), user.getMerId());
            if(device != null){
                ConfigPlan configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                if(configPlan != null){
                    //发送提现审核成功文本消息
                    SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getTbId(), configPlan.getMerId());
                    if(sysPlugin != null){
                        //发送提现审核成功文本消息
                        JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                        if(jsonObject != null){
                            //淘宝处罚订单回复买家
                            String message = jsonObject.getString("punish_reply_buyer");
                            if(StringUtils.isNotBlank(message)){
                                message = message.replace("[昵称]", Tools.getStr(user.getNickName()));
                                message = message.replace("[商品标题]", Tools.getStr(tbOrder.getTitle()));
                                message = message.replace("[订单编号]", Tools.getStr(tbOrder.getChildOrderNo()));
                                message = message.replace("[付款金额]", String.valueOf(Tools.getDouble(tbOrder.getPayment())));
                                message = message.replace("[收回金额]", String.valueOf(Tools.getDouble(tbOrder.getReUserBal())));
                                message = message.replace("[收回积分]", String.valueOf(Tools.getInteger(tbOrder.getReUserInte())));
                                message = message.replace("[账户余额]", String.valueOf(Tools.getDouble(user.getBalance())));
                                String cmsGoodListUrl = cmsParamReplaceService.getCmsGoodListUrl(tbOrder.getMerId(), user.getId(), user.getDeviceUniqueId());
                                message = message.replace("[订单列表]", Tools.getStr(cmsGoodListUrl));

                                //发送MQ消息
                                MsgDto<NoticeMsgDto>  msgDto = new MsgDto<>();
                                NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                                msgDto.setContent(noticeMsgDto);
                                msgDto.setId(IdWorker.getId());
                                msgDto.setDeviceType(device.getRecvmsgType());
                                msgDto.setDeviceUniqueId(device.getId());
                                msgDto.setMerId(tbOrder.getMerId());
                                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                                noticeMsgDto.setContent(message);
                                noticeMsgDto.setBizUserId(user.getBizUserId());
                                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                                noticeMsgDto.setGroupId(null);
                                noticeMsgDto.setNickName(user.getNickName());
                                noticeMsgDto.setMsgSource(1);
                                noticeMsgDto.setDelay(0);
                                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                                noticeMsgPushProducerService.sendMessage(msgDto);

                                logger.info("发送淘宝订单维权回复消息，para={}", JSONObject.toJSONString(msgDto));

                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 处理淘宝处罚订单业务功能
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbToken
     * @return null
     */
    public Long getOrders(TaobaoClient client,String date,Long pageno, TbToken tbToken) {
        TbkScPunishOrderGetRequest req = new TbkScPunishOrderGetRequest();
        TbkScPunishOrderGetRequest.TopApiAfOrderOption obj = new TbkScPunishOrderGetRequest.TopApiAfOrderOption();
        obj.setSpan(30l);
        obj.setPageSize(20l);
        obj.setPageNo(pageno);
        obj.setStartTime(com.taobao.api.internal.util.StringUtils.parseDateTime(date));
        req.setAfOrderOption(obj);
        try {
            TbkScPunishOrderGetResponse rsp = client.execute(req, tbToken.getAccessToken());
            if (rsp.getResult() != null) {
                TbkScPunishOrderGetResponse.PageResult result = rsp.getResult().getData();
                if (result != null) {
                    List<TbkScPunishOrderGetResponse.Result> datas = result.getResults();
                    if (datas != null && datas.size() > 0) {
                        for (TbkScPunishOrderGetResponse.Result data : datas) {
                            // 查询订单是否存在
                            TbPunishOrder tbPunishOrder = tbPunishOrderMapper.selectByTbTradeId(String.valueOf(data.getTbTradeId()), tbToken.getMerId());
                            if (tbPunishOrder != null) {
                                continue;
                            }
                            try {
                                tbPunishOrderAddService.add(data, tbToken);
                            } catch (Exception e) {
                                logger.error("add tb punish order err:", e);
                            }
                        }
                    }
                    Long totalCount = result.getTotalCount();
                    return totalCount;
                }
                return null;
            }
            return null;
        } catch(Exception e){
            logger.error("get punish order err:", e);
            return null;
        }
    }

    /**
     * 处理淘宝处罚订单业务功能
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param nowUser
     * @return null
     */
    private void updateBalance(double newBalance,int integral, int now, User nowUser,int awardType, String orderNo, Long sourceId, Long deviceUniqueId, String tradeno) {
        User user = new User();
        user.setId(nowUser.getId());
        user.setMerId(nowUser.getMerId());
        user.setDeviceType(nowUser.getDeviceType());
        user.setUpdateTime(now);
        user.setVersion(nowUser.getVersion());
        user.setBalance(Math.sub(nowUser.getBalance(), newBalance));
        user.setIntegral(nowUser.getIntegral() + integral);

        logger.info("--user={}",JSONObject.toJSONString(user));

        int count = userService.updateBalance(user);
        if (count==0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
        }

        UserAccDetail dub = new UserAccDetail();
        dub.setId(IdWorker.getId());
        dub.setTradeno(tradeno);
        dub.setMerId(nowUser.getMerId());
        dub.setUserId(nowUser.getId());
        dub.setDeviceUniqueId(deviceUniqueId);
        dub.setDeviceType(nowUser.getDeviceType());
        dub.setChangeInte(integral);
        dub.setChangeBal(0-newBalance); //扣除变动金额就是负数
        dub.setNewInte(nowUser.getIntegral());
        dub.setNewBal(user.getBalance());
        dub.setType(awardType);
        dub.setOrderId(orderNo);
        dub.setSourceUserId(sourceId);
        dub.setCreateTime(now);
        dub.setUpdateTime(now);

        //插入用户账户明细记录
        int insert = userAccDetailMapper.insert(dub);
        if(insert!=1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
        }

    }

    /**
     * 上传淘宝处罚订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbPunishOrderExcelDemoList
     * @return null
     */
    public void uploadTbPunishOrderFile(List<TbPunishOrderExcelDemo> tbPunishOrderExcelDemoList, TbPunishOrderUpLoadDto tbPunishOrderUpLoadDto){

        Integer now = DateUtil.getTime();

        Integer settleMonth =  tbPunishOrderUpLoadDto.getSettleMonth();
        Integer violationType = tbPunishOrderUpLoadDto.getViolationType();

        if(settleMonth == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入结算月份");
        }

        if(violationType == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入处罚类型");
        }

        if(tbPunishOrderExcelDemoList != null && tbPunishOrderExcelDemoList.size() > 0){
            for (TbPunishOrderExcelDemo tbPunishOrderExcelDemo : tbPunishOrderExcelDemoList){

                String childOrderNo = Tools.getStr(tbPunishOrderExcelDemo.getChildOrderNo());

                if(childOrderNo.contains(":")){
                    String[] transId = childOrderNo.split(":");
                    if(transId != null && transId.length == 2){
                        tbPunishOrderExcelDemo.setChildOrderNo(transId[1]);
                    }
                }
                // 查询订单是否存在
                TbPunishOrder tbPunishOrder = tbPunishOrderMapper.selectByTbTradeId(String.valueOf(tbPunishOrderExcelDemo.getChildOrderNo()), tbPunishOrderUpLoadDto.getMerId());
                if (tbPunishOrder != null) {
                    continue;
                }
                try {
                    tbPunishOrderAddService.addByUpload(tbPunishOrderExcelDemo, tbPunishOrderUpLoadDto);
                } catch (Exception e) {
                    logger.error("add tb punish order err:", e.getMessage());
                }
            }
        }
    }

    /**
     * 悠哉工具箱上传淘宝处罚订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param uploadTbPunishOrderByUzaiToolBoxDto
     * @return null
     */
    public void uploadTbPunishOrderByUzaiToolBox(UploadTbPunishOrderByUzaiToolBoxDto uploadTbPunishOrderByUzaiToolBoxDto){

        logger.info("--悠哉工具箱上传淘宝处罚订单-merId={}", uploadTbPunishOrderByUzaiToolBoxDto.getMerId());

        if(uploadTbPunishOrderByUzaiToolBoxDto.getMerId() == null ){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请上传运营商id");
        }

        String orders = uploadTbPunishOrderByUzaiToolBoxDto.getOrders();
        if(StringUtils.isBlank(orders)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请上传订单信息");
        }

        List<UploadTbPunishOrderByUzaiToolBoxDto.PunishOrderInfo> orderList = JSONObject.parseArray(orders, UploadTbPunishOrderByUzaiToolBoxDto.PunishOrderInfo.class);

        if(orderList == null || orderList.size() == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请上传订单信息");
        }

        for (UploadTbPunishOrderByUzaiToolBoxDto.PunishOrderInfo punishOrderInfo : orderList) {
            // 查询订单是否存在
            TbPunishOrder tbPunishOrder = tbPunishOrderMapper.selectByTbTradeId(String.valueOf(punishOrderInfo.getChildOrderNo()), uploadTbPunishOrderByUzaiToolBoxDto.getMerId());
            if (tbPunishOrder != null) {
                continue;
            }
            try {
                tbPunishOrderAddService.addByUploadByUzaiToolsBox(punishOrderInfo, uploadTbPunishOrderByUzaiToolBoxDto.getMerId());
            } catch (Exception e) {
                logger.error("addByUploadByUzaiToolsBox tb punish order err:", e.getMessage());
            }
        }

    }

    /**
     * 处罚订单查询结果导出文件前检验接口
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param tbPunishOrderQuery
     */
    public ExportAmountVo getExportAmount(TbPunishOrderQuery tbPunishOrderQuery){
        //执行分页查询对象
        Page<TbPunishOrder> page = new Page<>();
        tbPunishOrderQuery.convert(page);
        List<TbPunishOrder> tbPunishOrderList =  tbPunishOrderMapper.findByList(page, tbPunishOrderQuery);
        if(tbPunishOrderList == null || tbPunishOrderList.size() == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询结果记录数为0");
        }
        //单个机器人查询总数
        long totalCount = page.getTotal();
        if(totalCount == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询结果记录数为0");
        }

        String price = sysConfigMapper.selectByKey("export_record_price");

        //计算本次导出费用
        double amountTotal = 0.00D;
        if(amountTotal <= 10000){ //少于1万条，只收取1元
            amountTotal = 1.00D;
        }else{//总导出数大于1万条，则根据单价来计算，超过1万条的按照100条的单价费用来计算
            amountTotal = com.uzai.common.utils.Math.add(1.0D, ((totalCount - 10000)/100 + 1) * Double.parseDouble(price));
        }
        ExportAmountVo  exportAmountVo = new ExportAmountVo();
        exportAmountVo.setAmountTotal(amountTotal);
        exportAmountVo.setCountTotal(totalCount);
        exportAmountVo.setPrice(Double.parseDouble(price));

        return exportAmountVo;
    }

    /**
     * 处罚订单查询结果导出数据
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbPunishOrderExportResultDto
     * @return null
     */
    public void exportByQeuryResult(TbPunishOrderExportResultDto tbPunishOrderExportResultDto){
        if(tbPunishOrderExportResultDto.getMerId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if(StringUtils.isBlank(tbPunishOrderExportResultDto.getCode())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入验证码");
        }

        Merchant merchant = merchantMapper.selectById(tbPunishOrderExportResultDto.getMerId());
        if(merchant == null ){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //查询输入的验证码是否为系统默认密码
        if(!tbPunishOrderExportResultDto.getCode().equals(uzaiConsoleSysConfig.getDefaultPassword())){
            //获取存在redis中的验证码
            String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.SPECIAL_OPERATE.getDesc(), merchant.getMobile()));
            //判断验证码是否过期
            if (StringUtils.isBlank(codeByRedis)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
            }

            //验证码是否正确
            if (!codeByRedis.equals(tbPunishOrderExportResultDto.getCode())){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
            }
        }

        //页面查询条件
        TbPunishOrderQuery tbPunishOrderQuery = tbPunishOrderExportResultDto.getTbPunishOrderQuery();
        tbPunishOrderQuery.setMerId(tbPunishOrderExportResultDto.getMerId());

        //计算费用
        ExportAmountVo exportAmountVo = getExportAmount(tbPunishOrderQuery);

        //生成ZIP文件流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream out = new ZipOutputStream(outputStream);

        //每个excel表格订单最大数为10000条
        int exportExcelMaxNum = Const.ExprotFile.EXPORT_EXCEL_MAX_NUM;
        //导出excel文件序号
        int exportFileNumber = 0;

        //分页查询（每页1000条）
        //执行分页查询对象
        Page<TbPunishOrder> page = new Page<>();
        page.setCurrent(1); //只查第一页
        page.setSize(10); //每页查询100个
        page.addOrder(OrderItem.asc("id"));//默认id升序
        Long idStart = 0L;

        //存放导出文件对象(一万条一个表格)
        List<TbPunishOrderExport> tbPunishOrderExportList = new ArrayList<>();

        ArrayList<TbPunishOrder> tbPunishOrderList =  tbPunishOrderMapper.findByList(page, tbPunishOrderQuery);
        while (tbPunishOrderList != null && tbPunishOrderList.size() > 0) {
            for (TbPunishOrder tbPunishOrder : tbPunishOrderList) {
                if (tbPunishOrder.getId().longValue() > idStart.longValue()) {
                    idStart = tbPunishOrder.getId();
                }
                TbPunishOrderExport tbPunishOrderExport = new TbPunishOrderExport();
                BeanUtils.copyProperties(tbPunishOrder, tbPunishOrderExport);
                TbPunishOrderViolationTypesEnum tbPunishOrderViolationTypesEnum = TbPunishOrderViolationTypesEnum.getById(tbPunishOrder.getViolationType());
                if(tbPunishOrderViolationTypesEnum != null){
                    tbPunishOrderExport.setViolationTypeName(tbPunishOrderViolationTypesEnum.getDesc());
                }
                if(Tools.getInteger(tbPunishOrder.getStatus()).intValue() == 1){
                    tbPunishOrderExport.setStatusName("已扣款");
                }else{
                    tbPunishOrderExport.setStatusName("未处理");
                }

                TbToken tbToken = tbTokenMapper.selectById(tbPunishOrder.getTbTokenId(), tbPunishOrder.getMerId());
                if(tbToken != null){
                    tbPunishOrderExport.setUserName(tbToken.getUserName());
                }
                tbPunishOrderExportList.add(tbPunishOrderExport);

                //判断条数，如果条数大于10000条，生成excel文件
                if(tbPunishOrderExportList.size() >= exportExcelMaxNum){
                    ByteArrayOutputStream byteArrayOutputStream = null;
                    try {
                        //导出的文件序号,每次导出+1
                        exportFileNumber ++ ;
                        String fileName = "淘宝处罚订单_" + exportFileNumber +".xlsx";
                        //创建流
                        byteArrayOutputStream = new ByteArrayOutputStream();
                        //打包成ZIP文件
                        EasyExcel.write(byteArrayOutputStream, TbPunishOrderExport.class).registerConverter(new LongStringConverter()).sheet("淘宝处罚订单").doWrite(tbPunishOrderExportList);
                        ZipUtils.zip(out, new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), fileName);
                        byteArrayOutputStream.close();
                        //清空本次导出的数据列表
                        tbPunishOrderExportList.clear();
                    }catch (Exception e){
                        if(byteArrayOutputStream != null){
                            try {
                                byteArrayOutputStream.close();
                            } catch (IOException ex) {
                                logger.error(ex.getMessage(), ex);
                            }
                        }
                        logger.error("----导出淘宝处罚订单异常--error={}", e.getMessage());
                    }
                }
            }
            //循环查询下一页
            tbPunishOrderQuery.setIdStart(idStart);
            tbPunishOrderList = tbPunishOrderMapper.findByList(page, tbPunishOrderQuery);
        }

        //最后将剩余不足10000条的记录，生成excel文件
        if(tbPunishOrderExportList.size() > 0){
            ByteArrayOutputStream byteArrayOutputStream = null;
            try {
                //导出的文件序号,每次导出+1
                exportFileNumber ++ ;
                String fileName = "淘宝处罚订单_" + exportFileNumber +".xlsx";
                //创建流
                byteArrayOutputStream = new ByteArrayOutputStream();
                //打包成ZIP文件
                EasyExcel.write(byteArrayOutputStream, TbPunishOrderExport.class).registerConverter(new LongStringConverter()).sheet("淘宝处罚订单").doWrite(tbPunishOrderExportList);
                ZipUtils.zip(out, new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), fileName);
                byteArrayOutputStream.close();
                //清空本次导出的数据列表
                tbPunishOrderExportList.clear();
            }catch (Exception e){
                if(byteArrayOutputStream != null){
                    try {
                        byteArrayOutputStream.close();
                    } catch (IOException ex) {
                        logger.error(ex.getMessage(), ex);
                    }
                }
                logger.error("----导出淘宝处罚订单异常--error={}", e.getMessage());
            }
        }

        try {
            // 注意关闭流的顺序，在上传oss之前必须关闭流否则下载解压的时候会报“文件末端错误”的问题
            outputStream.close();
            out.close();
        }catch (Exception e){
            logger.error("----上传淘宝处罚订单关闭流异常--error={}", e.getMessage());
        }finally {

        }

        //上传文件到OSS当中
        InputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
        String zipFileName = "淘宝处罚订单_" + System.currentTimeMillis() + ".zip";
        //上传文件通讯录
        exportInfoService.uploadExportFile(byteArrayInputStream, tbPunishOrderExportResultDto.getMerId(), zipFileName, exportAmountVo, ExportInfoTypeEnum.EXPORT_INFO_TB_PUSISH_ORDER.getId());

    }


    /**
     * 查询淘宝处罚订单是否自动扣款
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public TbPunishOrderAutoChargebackVo findAutoChargeback(Long merId){
        TbPunishOrderAutoChargebackVo tbPunishOrderAutoChargebackVo = new TbPunishOrderAutoChargebackVo();

        //查询当前运营商的设备类型配置
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.TB_PUNISH_ORDER_AUTO_CHARGEBACK.getValue());
        if(merBaseConfig != null && StringUtils.isNotBlank(merBaseConfig.getVal())){
            try {
                int autoChargeback = Integer.parseInt(merBaseConfig.getVal());
                tbPunishOrderAutoChargebackVo.setAutoChargeback(autoChargeback);
            }catch (Exception e){
                logger.error("--淘宝处罚订单自动扣款设置格式错误--result={}",merBaseConfig.getVal());
            }
        }
        return tbPunishOrderAutoChargebackVo;
    }

    /**
     * 修改淘宝处罚订单是否自动扣款
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbPunishOrderAutoChargebackDto
     * @return null
     */
    public void updateAutoChargeback(TbPunishOrderAutoChargebackDto tbPunishOrderAutoChargebackDto){
        //设置数据库的数据
        Integer currentTime = com.uzai.console.common.utils.DateUtil.getNowTime();

        Long merId = tbPunishOrderAutoChargebackDto.getMerId();

        //查询当前运营商的设备类型配置
        MerBaseConfig merBaseConfig_old = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.TB_PUNISH_ORDER_AUTO_CHARGEBACK.getValue());

        if(merBaseConfig_old != null){ //如果存在，则修改
            //修改设备开关配置
            merBaseConfig_old.setVal(String.valueOf(tbPunishOrderAutoChargebackDto.getAutoChargeback()));
            merBaseConfig_old.setUpdateTime(currentTime);
            merBaseConfigMapper.update(merBaseConfig_old);
        }else{ //如果没配置，新增配置
            MerBaseConfig merBaseConfig_new = new MerBaseConfig();
            merBaseConfig_new.setId(IdWorker.getId());
            merBaseConfig_new.setMerId(merId);
            merBaseConfig_new.setType(MerConfigTypeEnum.PRODUCTS.getValue());
            merBaseConfig_new.setKey(MerConfigKeyEnum.TB_PUNISH_ORDER_AUTO_CHARGEBACK.getValue());
            merBaseConfig_new.setVal(String.valueOf(tbPunishOrderAutoChargebackDto.getAutoChargeback()));
            merBaseConfig_new.setCreateTime(currentTime);
            merBaseConfig_new.setUpdateTime(currentTime);
            merBaseConfigMapper.insert(merBaseConfig_new);
        }
    }


}
